package turtle.daily;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;

import arbor.mining.util.stock.StockEntity;
public class TaifexCrawler {
	
	public static String TAIFEX_FN = "data/taifex.csv";
	public TaifexCrawler() {
		
	}
	public ArrayList<StockEntity> getHistory() {
		ArrayList<StockEntity> list = new ArrayList<StockEntity>();
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		try {
			BufferedReader reader = new BufferedReader(new FileReader(TAIFEX_FN));
            String line, curDate="";
            reader.readLine(); /*The first line is title*/
			/**
			 * Parse the content as HLOC list.
			 */
			while ((line=reader.readLine())!=null) {	
			      Date day = null;
			      
			      GregorianCalendar startTime = new GregorianCalendar();
			      GregorianCalendar endTime = new GregorianCalendar();
			      String[] token = line.split(",");
			      try {
			    	  day = df.parse(token[0]);
				  } catch (ParseException e) {
					  System.out.println(e);
				  } 
				  if (!token[0].equals(curDate)) {
				    curDate = token[0];
				    startTime.setTime(day);
				    startTime.set(Calendar.HOUR_OF_DAY, 9);			  
				    endTime.setTime(day);
				    endTime.set(Calendar.HOUR_OF_DAY, 13);
				    endTime.set(Calendar.MINUTE, 30);
				  
			        StockEntity entity = new StockEntity(StockEntity.RANGE_TYPE_DAY, startTime, endTime);
			        entity.ohlc.open = Double.parseDouble((token[2])); 		    	
			        entity.ohlc.high = Double.parseDouble((token[3]));
			        entity.ohlc.low = Double.parseDouble((token[4]));
			        entity.ohlc.close = Double.parseDouble((token[5]));
			        entity.volume = Integer.parseInt((token[6]));
			        list.add(entity);
				  }
			    }					
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
    public static void main(String[] args) {
    	new TaifexCrawler().getHistory();
    }	
}
